using Microsoft.AspNetCore.Mvc;
using TodoApi.Models;
using TodoApi.Services;

namespace TodoApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class TodoController : ControllerBase
    {
        private readonly ITodoService _todoService;

        public TodoController(ITodoService todoService)
        {
            _todoService = todoService;
        }

        // 获取所有待办事项
        [HttpGet]
        public IActionResult GetAll()
        {
            var todos = _todoService.GetAll();
            return Ok(todos);
        }

        // 获取单个待办事项
        [HttpGet("{id}")]
        public IActionResult GetById(int id)
        {
            var todo = _todoService.GetById(id);
            if (todo == null)
                return NotFound();

            return Ok(todo);
        }

        // 创建待办事项
        [HttpPost]
        public IActionResult Create([FromBody] TodoItem todoItem)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            _todoService.Add(todoItem);
            return CreatedAtAction(nameof(GetById), new { id = todoItem.Id }, todoItem);
        }

        // 更新待办事项
        [HttpPut("{id}")]
        public IActionResult Update(int id, [FromBody] TodoItem todoItem)
        {
            if (id != todoItem.Id)
                return BadRequest();

            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            var existingTodo = _todoService.GetById(id);
            if (existingTodo == null)
                return NotFound();

            _todoService.Update(todoItem);
            return NoContent();
        }

        // 删除待办事项
        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            var todo = _todoService.GetById(id);
            if (todo == null)
                return NotFound();

            _todoService.Delete(id);
            return NoContent();
        }
    }
}    